let imgUrl = '';

$(function () {
    let markId = getUrlString('markid');



    let Dictionary = function(){
        this.data = [];
        this.find = find;
        this.add = add;
    };

    let find = function(key){
        return this.data[key]
    };

    let add = function(key,value){
        this.data[key]=value
    };

    var type = new Dictionary();




    //获取分类
    let categoryTypeVal = [];
    let nameVal = [];
    //左侧分类列表
    function getList (){
        let data = {
            'markid':markId
        };
        getData('post','/niu/apiv4/niu_category.php',data,function (data) {
            console.log(data);
            let append = '';
            $(data.info).each(function () {
                type.add(this.name,this.type);
                categoryTypeVal.push(this.name)
            });
        });
    }

    getList();


    function getType (){
        let data = {
            'markid':markId,
            'sort':'1'
        };
        getData('post','/niu/apiv4/niu_makersworks.php',data,function (data) {
            console.log(data);
            let mainAppend = '';
            $.each(data.mainseriosData,function (key,item) {
                mainAppend += '<li class="classify">' +
                    '                <div class="classifyName">'+key+'</div>' ;
                $(item).each(function () {
                    mainAppend+= '<div class="classifyLi">'+this.name+'</div>' ;
                });
                mainAppend += '            </li>'
            });
            $('#classifyUl').append(mainAppend);

            $('#classifyUl li .classifyLi').click(function () {
                $('#mainseries').html($(this).html());
                $('#productionIndex').removeClass('bounceInUp').addClass('bounceOutUp');
            });

            $('#productionIndex .indexAlert').click(function () {
                $('#productionIndex').removeClass('bounceInUp').addClass('bounceOutUp');
            });



            $('#productionIndex .indexes li').click(function () {
                let index = $(this).index();
                // let height = .height();
                let height = 0;
                for (var i = 0;i < index;i++){
                    height += jq('#classifyUl li').eq(i).height()
                }
                // console.log(height);
                jq('#productionContent').animate({
                        scrollTop: height
                    }, 500
                );
            });

            jq("#productionContent").scroll(function () {
                $('#classifyUl li .classifyName').each(function (i) {
                    let H = $('#classifyUl li .classifyName').eq(i).offset().top;
                    let bodyH = $('body').height() * 0.2;
                    if (H < bodyH + 1){
                        $('#productionIndex .indexes li').removeClass('active').eq(i).addClass('active');
                    }
                });
            });

            let makerAppend = '';
            $.each(data.makerData,function (key,item) {
                makerAppend += '<li class="classify">' +
                    '                <div class="classifyName">'+key+'</div>' ;
                $(item).each(function () {
                    makerAppend+= '<div class="classifyLi">'+this.name+'</div>' ;
                });
                makerAppend += '            </li>'
            });
            $('#markerData').append(makerAppend);
            $('#markerData li .classifyLi').click(function () {
                $('#makerName').html($(this).html());
                $('#markerIndex').removeClass('bounceInUp').addClass('bounceOutUp');
            });
            $('#markerIndex .indexAlert').click(function () {
                $('#markerIndex').removeClass('bounceInUp').addClass('bounceOutUp');
            });
            $('#markerIndex .indexes li').click(function () {
                let index = $(this).index();
                // let height = .height();
                let height = 0;
                for (var i = 0;i < index;i++){
                    height += jq('#markerData li').eq(i).height()
                }
                jq('#markerContent').animate({
                        scrollTop: height
                    }, 500
                );
            });

            jq("#markerContent").scroll(function () {
                $('#markerData li .classifyName').each(function (i) {
                    let H = $('#markerData li .classifyName').eq(i).offset().top;
                    let bodyH = $('body').height() * 0.2;
                    if (H < bodyH + 1){
                        $('#markerIndex .indexes li').removeClass('active').eq(i).addClass('active');
                    }
                });
            });
        })
    }

    getType();

    //选择作品
    $('#production').click(function () {
        $('#productionIndex').show().removeClass('bounceOutUp').addClass('bounceInUp')
    });

    //选择制造商
    $('#marker').click(function () {
        $('#markerIndex').show().removeClass('bounceOutUp').addClass('bounceInUp')
    });


    // //获取token
    // function getToken () {
    //     let data = {
    //         'markid':markId
    //     };
    //     getData('post','/niu/apiv4/qiniu_token.php',data,function (data) {
    //         // console.log(data)
    //         qiniutoken = data.token
    //     })
    // }
    // getToken();
    //
    // //七牛token 七牛云平台安全标识
    // var qiniutoken = '';
    // //七牛云图片base64格式上传地址
    // var uploadUrl = "http://upload.qiniup.com/putb64/-1";
    // //需要上传的图片内容 base64格式
    // var imgStr = '';
    //
    // //七牛云平台 配置的域名
    // var urlHeader = "https://img3.odancool.com/";
    //
    // let imgUrl = '';
    // //上传图片
    // function uploadImg() {
    //     var xhr = new XMLHttpRequest();
    //     xhr.open("POST", uploadUrl, true);
    //     //文本类型
    //     xhr.setRequestHeader("Content-Type", "application/octet-stream");
    //     //七牛认证信息 注意空格
    //     xhr.setRequestHeader("Authorization", "UpToken " + qiniutoken);
    //     xhr.send(imgStr);
    //     //监听状态
    //     xhr.onreadystatechange = function() {
    //         if(xhr.readyState === 4) {
    //             var result = xhr.responseText;
    //             console.log('上传请求结果数据:' + result);
    //             result = JSON.parse(result);
    //             imgUrl = urlHeader + result.hash;
    //             $('.selectImgLi').html('<img src="'+urlHeader + result.hash+'" alt="">');
    //         }
    //     }
    //
    // }
    //
    // //将图片转为base64格式的字符串
    // //图片上传到七牛云
    // $('#thumb').on('change', function() {
    //     var reader = new FileReader();
    //     //filses就是input[type=file]文件列表，files[0]就是第一个文件，这里就是将选择的第一个图片文件转化为base64的码
    //     reader.readAsDataURL(this.files[0]);
    //     reader.onload = function(e) {
    //         imgStr = reader.result.split(',')[1];
    //         uploadImg();
    //     }
    // });



    // $("#categoryType").picker("setValue", ["2012", "12", "12"]);

    $("#categoryType").picker({
        toolbarTemplate: '<header class="bar bar-nav">\
          <button class="button button-link pull-right close-picker">确定</button>\
          <h1 class="title">请选择商品类别</h1>\
        </header>',
        cols: [
            {
                textAlign: 'center',
                values: categoryTypeVal
            }
        ]
    });

    $('#qdbtn').click(function () {
        let name = $('#title').val();
        let mainseries = $('#mainseries').html();
        let maker = $('#makerName').html();
        let maintype = type.find($('#categoryType').val());
        let price = $('#price').val();
        let remark = $('#remark').val();
        let book_time = $('#datetime').val().substring(0,4)+$('#datetime').val().substring(5,7);

        if (name === ''){
            $.toast('请输入标题');
            return
        }

        if (mainseries === '请选择作品') {
            $.toast('请选择作品');
            return
        }

        if (maintype === undefined){
            $.toast('请选择商品类别');
            return
        }

        if (book_time === ''){
            $.toast('请选择发售时间');
            return
        }

        if (maker === '请选择制造商') {
            $.toast('请选择制造商');
            return
        }

        if (price === ''){
            $.toast('请输入官方定价');
            return
        }

        if (imgUrl === ''){
            $.toast('请上传图片');
            return
        }

        let data = {
            'markid':markId,
            'name':name,
            'mainseries':mainseries,
            'maintype':maintype,
            'book_time':book_time,
            'maker':maker,
            'price':price,
            'pics':imgUrl,
            'intro2':remark
        };
        console.log(data);
        getData('post','/niu/apiv4/niu_user_addgoods.php',data,function (data) {
            console.log(data);
            if (data.resultcode === 200){
                // $.toast(data.msg);
                $.toast(data.msg);
                setTimeout(function () {
                    nativeCommand("dancool://activity=fin")
                },500)
            }else {
                $.toast(data.msg)
            }
        })
    });

    $('#datetime').calendar({
        value: ["2020-09-01"]
    });
});

$('#upLoad').click(function () {
    getnative("dancool://uploadfile=1");
});

function jsnativeresult (aaa,bbb,ccc) {
    if (ccc !== '' || ccc !== null){
        imgUrl = ccc;
        $('#upLoad').hide()
    }
    let text='<div class="selectImgLi">' +
        '            <img src="'+ccc+'" alt="">' +
        '            <img class="closeAlert" src="../../res/img/common/delete.png" alt="">'+
        '        </div>';
    //添加结点
    // $(text).insertBefore($("#uploadimgadd"));
    $('#selectImg').append(text);

    $('#selectImg .closeAlert').click(function () {
        imgUrl = '';
        $('#upLoad').show();
        $(this).parent().remove()
    });

}


function getnative(actionurl) {
    var u = navigator.userAgent;
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
    var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
    if (isiOS) {
        window.webkit.messageHandlers.getnative.postMessage(actionurl);
    }else {
        ikags.getnative(actionurl)
    }
}
